import React, { FC } from 'react';
import { Form, Row, Col, Button, Card, message, Flex } from 'antd';
import {
  MinioUploadListType,
  MinioUpload,
  FormPanel,
  type FormPanelObject,
  FormPanelStatus,
  RuleType,
  InputType,
  useAuth,
} from 'lfun-bg-comp';
import dayjs from 'dayjs';
import styles from './index.less';
import { GENDER } from '@/constant/basicOptions';
import { ID_TYPE } from '@/constant/studentOptions';
import SearchInput from '@/view/component/searchInput';
import { searchSchool } from '@/service/unit/school';
import FormPanelWrapper from './FormPanelWrapper';
import { searchSchoolOptions } from '@/service/options';

const list = [
  {
    title: '',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    span: 12,
    inputs: [
      {
        label: '姓名',
        name: 'teacher_name',
        key: 'teacher_name',
        required: true,
        // span: 24,
        // props: {
        //   labelCol: { span: 4 },
        //   wrapperCol: { span: 20 },
        // },
        textRange: [0, 20],
        inputType: InputType.text,
      },
      {
        label: '性别',
        name: 'teacher_gender',
        key: 'teacher_gender',
        required: true,
        inputType: InputType.select,
        renderOption: GENDER,
      },
      {
        label: '证件类型',
        name: 'teacher_id_type',
        key: 'teacher_id_type',
        required: true,
        relationFields: ['teacher_id_number'],
        inputType: InputType.select,
        renderOption: ID_TYPE,
      },
      {
        label: '证件号码',
        name: 'teacher_id_number',
        key: 'id_number',
        required: true,
        textRange: [0, 30],
        hidden: (formPanelObject: FormPanelObject) => {
          return formPanelObject.getFieldsValue().teacher_id_type === 'resident_id_card';
        },
      },
      {
        label: '证件号码',
        name: 'teacher_id_number',
        key: 'teacher_id_number',
        inputType: InputType.text,
        required: true,
        ruleType: RuleType.cnPeopleNo,
        textRange: [0, 20],
        hidden: (formPanelObject: FormPanelObject) => {
          return formPanelObject.getFieldsValue().teacher_id_type !== 'resident_id_card';
        },
      },
      {
        label: '出生日期',
        name: 'teacher_date_of_birth',
        key: 'teacher_date_of_birth',
        required: true,
        inputType: InputType.date,
      },
      // {
      //   label: '任职单位',
      //   name: 'teacher_employer',
      //   key: 'teacher_employer',
      //   required: true,
      //   inputType: InputType.search,
      //   renderOption: async (form: FormPanelObject, searchTxt: string) => {
      //     const list = await searchSchoolOptions(form, searchTxt, form.getFieldValue('teacher_employer'));
      //     return list;
      //   },
      //   // children: (
      //   //   <SearchInput
      //   //     onLoadOption={null}
      //   //     searchFunction={async v => {
      //   //       const { success, data } = await searchSchool(v, 1, 50);
      //   //       if (success) {
      //   //         return data.items.map(item => ({
      //   //           label: item.school_name,
      //   //           value: item.id,
      //   //         }));
      //   //       }
      //   //       return [];
      //   //     }}
      //   //     randerOption={option => option}
      //   //   />
      //   // ),
      // },
      {
        label: '手机号',
        name: 'mobile',
        key: 'mobile',
        required: true,
        ruleType: RuleType.cnPhone,
      },
    ],
  },
];
// eslint-disable-next-line react/require-default-props
const Groups: FC<{ isEdit?: boolean; onLoad?: (cntForm, photoForm) => void; formValue?: any; api?: any }> = ({
  isEdit = true,
  onLoad,
  formValue = {},
  api = {},
}) => {
  const photoForm = Form.useForm()[0];
  const [form, setForm] = React.useState<any>({ teacher_date_of_birth: '' });
  const [showFormModel, setFormModel] = React.useState(false);
  const auth = useAuth();
  const user = auth?.user || {};
  console.log(user, '==========================>>>>');
  React.useEffect(() => {
    //console.log('🚀 ~ React.useEffect ~ formValue:', formValue);
    // formValue 是个对象，并且长度必须大于0
    if (Object.keys(formValue).length > 0) {
      setForm({ ...formValue });
      //photoForm.setFieldValue('teacher_avatar', formValue.teacher_avatar);
      if (formValue.teacher_avatar) {
        photoForm.setFieldValue('teacher_avatar', [
          {
            name: `${formValue.teacher_name}.jpg`, //formValue.teacher_avatar, //'2de902e1325adf2f82ebaffce3352a0.jpg',
            url: formValue.teacher_avatar_url, //'https://minio.f123.pub/demo/8868964926.jpg',
            uid: formValue.teacher_avatar,
          },
        ]);
      }
    }
  }, [formValue]);

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id: formValue.teacher_id,
      teacher_date_of_birth: dayjs(values.teacher_date_of_birth).format('YYYY-MM-DD'),
    };
    // 编辑
    // const res = await NewTeachersSrv.update(params);
    const res = await api.save(params);
    if (res.success) {
      message.success('修改成功');
      setFormModel(false);
      formPanelObject.resetFields();
      setForm(res.data);
    } else {
      formPanelObject.reVaildation(res.data);
    }
  };

  /** 头像 */
  const handlePhoto = async file => {
    // api.onSavePhoto(file);
    if (file && file.length) {
      const params = {
        ...form,
        teacher_id: formValue.teacher_id,
        teacher_avatar: String(file[0].uid),
      };

      if (form?.teacher_date_of_birth) {
        params.teacher_date_of_birth = dayjs(form?.teacher_date_of_birth).format('YYYY-MM-DD');
      }

      const res = await api.save(params);
      if (res.success) {
        message.success('保存成功');
        setForm(res.data);
        // init();
      }
      return res.success;
    }
    return false;
  };

  return (
    <Card className={styles.top_card}>
      <Row>
        <Col span="6" className={styles.poto}>
          <Form form={photoForm} disabled={!isEdit} style={{ marginTop: '30px' }}>
            {/* rules={[{ required: true, message: '请上传照片' }]} */}
            <Form.Item name="teacher_avatar" className={isEdit ? '' : 'non-edit'}>
              <MinioUpload
                listType={MinioUploadListType.pictureCard}
                supportFileTypes={['image/jpeg', 'image/jpg']}
                text="上传照片"
                fileNamePrefix={user.phone || user.name}
                isPrivate={false}
                uploadSrv="/school/v1/storage/school-upload-uri"
                onChange={file => {
                  //console.log(file, fileList);
                  handlePhoto(file);
                }}
                placeholder="上传支持JPG、JPEG文件大小60k,支持规格26mmx32mm"
              />
              {/* <span className={styles.poto_tip}>上传支持JPG、JPEG文件大小60k,支持规格26mmx32mm</span> */}
            </Form.Item>
          </Form>
        </Col>
        <Col span="18" className={styles.basic_top_info}>
          <div style={{ height: 32, marginBottom: '10px' }}>
            {isEdit && (
              <Flex style={{ justifyContent: 'flex-end' }}>
                <Button
                  type="primary"
                  onClick={() => {
                    //console.log(formValue, '======>>>>');
                    setFormModel(true);
                  }}
                >
                  关键信息变更
                </Button>
              </Flex>
            )}
          </div>

          <FormPanel
            onLoad={cntForm => {
              if (typeof onLoad === 'function') {
                onLoad(cntForm, photoForm);
              }
            }}
            formStatus={FormPanelStatus.nonEdit}
            buttonsDisplay="block"
            template={list}
            values={form}
          />
          <FormPanelWrapper
            title="关键信息变更"
            visible={showFormModel}
            formValue={form}
            isReset={false}
            //changeValue={setFormModel}
            formList={list}
            onCancel={(temp: boolean, formPanelObject: FormPanelObject) => {
              formPanelObject.resetFields();
              setForm({ ...formValue });
              setFormModel(false);
            }}
            onSave={handleSave}
          />
        </Col>
      </Row>
    </Card>
  );
};

export default Groups;
